/*
 * @Author: CPS
 * @Date: 2020-07-21 21:21:47
 * @Last Modified by: CPS
 * @Last Modified time: 2020-08-31 11:53:51
 * @Projectname Electron-fileWatcher
 * @Filename watcher.js
 */
'use strict'
import fs from 'fs'
import chokidar from 'chokidar'
import defaultOptions from './watcher.config.js'

/* 监听文件夹 */
function folderWatch(tarPath, listener) {
  let watcher
  if (!fs.lstatSync(tarPath)) return
  let fileList = fs.readdirSync(tarPath)

  // console.log('当前监听目录:' + tarPath)
  watcher = chokidar.watch(tarPath, defaultOptions)
    .on('ready', () => {
      console.log('文件夹已经准备好')
      if (!listener) return
      for (let each in listener) {
        console.log(each + ' 添加监听器.')
        watcher.on(each, listener[each])
      }
    })
  // .on('error', error => log(`Watcher error: ${error}`))
  // .on('add', path => log(`File ${path} has been added`))
  //   .on('change', path => log(`File ${path} has been changed`))
  //   .on('unlink', path => log(`File ${path} has been removed`));

  // watcher
  //   .on('addDir', path => log(`Directory ${path} has been added`))
  //   .on('unlinkDir', path => log(`Directory ${path} has been removed`))
  //   .on('ready', () => log('Initial scan complete. Ready for changes'))
  // .on('raw', (event, path, details) => { // internal
  //   log('Raw event info:', event, path, details);
  // });
  return watcher
}

if (require.main === module) {
  const path = require('path')
  let p = 'D:\\CPS\\MyProject\\Electron-fileWatcher\\design\\resource\\2020年\\7月'
  let P = 'D:\\CPS\\MyProject\\Electron-fileWatcher\\design\\resource\\2020年\\7月\\vvvb.xlsx'
  let w = folderWatch(p)

  console.log(path.basename(path.dirname(p)))
  console.log(path.basename(path.dirname(p)))
}

export default folderWatch
